﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Collections.ObjectModel;

namespace RaSuperGrid.XMLService
{

    public class XMLData
    {
        public XMLData()
        {
            m_FileName = "SuperGridData.xml";
            m_LoadedDocument = GetTestData();

            m_TransactionCollection = new ObservableCollection<Transaction>();

            var transactions = from t in m_LoadedDocument.Descendants("Transaction")
                                  select new Transaction
                                  {
                                      ID = Convert.ToInt32(t.Element("ID").Value),
                                      RequestDate = DateTime.Parse(t.Element("RequestDate").Value.ToString()),
                                      NeedByDate = DateTime.Parse(t.Element("NeedByDate").Value.ToString()),
                                      Urgency = t.Element("Urgency").Value,
                                      Reason = t.Element("Reason").Value,
                                      Requester = t.Element("Requester").Value,
                                      Contact = t.Element("Contact").Value,
                                      Cost = t.Element("Cost").Value,
                                      Repeatable = Boolean.Parse(t.Element("Repeatable").Value),
                                      Description = t.Element("Description").Value,
                                      Special = t.Element("Special").Value
                                  };

            foreach (var transaction in transactions)
            {
                Transaction t = new Transaction(transaction);

                m_TransactionCollection.Add(t);
            }

            
        }

        /// <summary> 
        /// Create a default empty data set. Use XDocument to create XML file. XElement create 
        /// elements under the XML tree. XML document 
        /// </summary> 
        public static XDocument GetEmptyData()
        {
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XComment("Supergrid Data"),
                new XElement("superGridData",
                    new XAttribute("creationDate", DateTime.Today.ToString("MMMM dd, yyyy")),
                    new XAttribute("version", "0.1"),
                    new XElement("Transactions")));

            return doc;
        }

        /// <summary> 
        /// Create a default test data set. Use XDocument to create XML file. XElement create 
        /// elements under the XML tree. XML document 
        /// </summary> 
        public static XDocument GetTestData()
        {
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XComment("Supergrid Data"),
                new XElement("superGridData",
                    new XAttribute("creationDate", DateTime.Today.ToString("MMMM dd, yyyy")),
                    new XAttribute("version", "0.1"),
                    new XElement("Transactions",
                        new XElement("Transaction",
                            new XElement("ID", "1"),
                            new XElement("RequestDate", "Sat, 01 Nov 2008 19:35:00 GMT"),
                            new XElement("NeedByDate", "Sat, 01 Nov 2008 19:35:00 GMT"),
                            new XElement("Urgency", "High"),
                            new XElement("Reason", "Doing Group"),
                            new XElement("Requester", "Lee"),
                            new XElement("Contact", "63668888"),
                            new XElement("Cost", "$5000"),
                            new XElement("Repeatable", "False"),
                            new XElement("Description", "Some transaction"),
                            new XElement("Special", "special behavior")),
                        new XElement("Transaction",
                            new XElement("ID", "2"),
                            new XElement("RequestDate", "Sat, 01 Nov 2008 19:35:00 GMT"),
                            new XElement("NeedByDate", "Sat, 01 Nov 2008 19:35:00 GMT"),
                            new XElement("Urgency", "Normal"),
                            new XElement("Reason", "Doing Group 2"),
                            new XElement("Requester", "Ching"),
                            new XElement("Contact", "63667777"),
                            new XElement("Cost", "$1000"),
                            new XElement("Repeatable", "True"),
                            new XElement("Description", "Some transaction too"),
                            new XElement("Special", "special cut")))));

            return doc;
        }

        /// <summary>
        /// Save data to an XML file 
        /// </summary>
        /// <param name="filename">Name of file to write data to</param>
        public static void SaveDataToXml()
        {
             m_LoadedDocument.Save(m_FileName);
        }

        /// <summary>
        /// Load data from XML file
        /// </summary>
        /// <param name="fileToLoad">Name of file to load data from</param>
        /// <returns>document loaded as XDocument</returns>
        public static void LoadDataFromXML()
        {
            m_LoadedDocument = XDocument.Load(m_FileName);
        }

        public static Transaction GetTransaction(int ID)
        {
            XDocument doc = m_LoadedDocument;
            return (from t in m_LoadedDocument.Descendants("Transaction")
                    where t.Element("ID").Value.Equals(ID.ToString())
                    select new Transaction()
                    {
                        ID = Convert.ToInt32(t.Element("ID").Value),
                       RequestDate = DateTime.Parse(t.Element("RequestDate").Value, System.Globalization.CultureInfo.InvariantCulture), 
                        NeedByDate = DateTime.Parse(t.Element("NeedByDate").Value, System.Globalization.CultureInfo.InvariantCulture), 
                        Urgency = t.Element("Urgency").Value,
                        Reason = t.Element("Reason").Value,
                        Requester = t.Element("Requester").Value,
                        Contact = t.Element("Contact").Value,
                        Cost = t.Element("Cost").Value,
                        Repeatable = Boolean.Parse(t.Element("Repeatable").Value),
                        Description = t.Element("Description").Value,
                        Special = t.Element("Special").Value

                    }).FirstOrDefault();
        }

        public static void DeleteTransaction(int transactionID)
        {
            XElement transaction = m_LoadedDocument.Descendants("Transaction").Where(t => t.Element("ID").Value.Equals(transactionID.ToString())).FirstOrDefault();
            if (transaction != null)
            {
                transaction.Remove();
                SaveDataToXml();
            }
        }

        private static int GetNextAvailableID()
        {
            return Convert.ToInt32(
                    (from c in m_LoadedDocument.Descendants("Transaction")
                     orderby Convert.ToInt32(c.Element("ID").Value) descending
                     select c.Element("ID").Value).FirstOrDefault()
                    ) + 1;
        }

        private static string m_FileName;
        private static string m_FilePath;
        private static XDocument m_LoadedDocument;

        public ObservableCollection<Transaction> m_TransactionCollection;
    }
}
